#!/bin/bash

function usage()
{
	echo -e "\nUsage: $0 <on|off|st|xHZ>\n"
	echo -e "  for example:"
	echo -e "    $0 on    --- turn on PWM"
	echo -e "    $0 off   --- turn off PWM"
	echo -e "    $0 st    --- get the PWM status"
	echo -e "    $0 30    --- turn on PWM, and set the frequency to 30HZ\n"
}

function pwm_operate()
{
	local opt=$1
	local sysfs_pwmchip="/sys/class/pwm/pwmchip3"
	if [[ ! -d ${sysfs_pwmchip}/pwm0 ]]; then
		echo 0 > ${sysfs_pwmchip}/export
	fi

	# The unit of period/duty_cycle is "ns"
	# 1000000000 ns == 1 s
	case ${opt} in
		"on")
			if [[ $(cat ${sysfs_pwmchip}/pwm0/period) == "0" ]]; then
				# set to 4hz
				echo 250000000 > ${sysfs_pwmchip}/pwm0/period
				echo  25000000 > ${sysfs_pwmchip}/pwm0/duty_cycle
			fi
			echo 1 > ${sysfs_pwmchip}/pwm0/enable

			let period_ms=$(cat ${sysfs_pwmchip}/pwm0/period)/1000/1000
			let freq=1000/${period_ms}
			echo "[INFO] PWM has turn ON, frequency=${freq}HZ"
			;;
		"off")
			echo 0 > ${sysfs_pwmchip}/pwm0/enable
			echo "[INFO] PWM has turn OFF"
			;;
		"st")
			if [[ ! -e ${sysfs_pwmchip}/pwm0/enable || \
				$(cat ${sysfs_pwmchip}/pwm0/enable) -eq 0 || \
				$(cat ${sysfs_pwmchip}/pwm0/period) -eq 0 ]]; then
				echo "[INFO] PWM is OFF"
			else
				let period_ms=$(cat ${sysfs_pwmchip}/pwm0/period)/1000/1000
				let freq=1000/${period_ms}
				echo "[INFO] PWM is ON, frequency=${freq}HZ"
			fi
			;;
		*)
			# Frequency specified must be an integer number
			if [[ ! ${opt} =~ ^[1-9][0-9]*$ ]]; then
				echo "[ERROR] Unsupport operation option: ${opt}"
				usage
				exit 1
			fi
			if [[ ${opt} -lt 1 || ${opt} -gt 1000 ]]; then
				echo "[ERROR] Invalid frequency: ${opt}"
				usage
				exit 1
			fi

			let period_ns=1000*1000*1000/${opt}
			let on_ns=${period_ns}/2
			let period_ms=${period_ns}/1000/1000
			let on_ms=${on_ns}/1000/1000

			echo ${period_ns} > ${sysfs_pwmchip}/pwm0/period
			echo ${on_ns}     > ${sysfs_pwmchip}/pwm0/duty_cycle
			echo 1 > ${sysfs_pwmchip}/pwm0/enable

			echo "[INFO] PWM has turn ON, frequency=${opt}HZ"
			echo "  Period_ms=${period_ms}"
			echo "  ON_ms=${on_ms}"
			echo "  Period_ns=${period_ns}"
			echo "  ON_ns=${on_ns}"
			;;
	esac
}

##################################################################

if [[ $# -lt 1 ]]; then
	usage
	exit 1
fi

if [[ $(id -u) -ne 0 ]]; then
	echo -e "[ERROR] Please run as root!"
	usage
	exit 1
fi

pwm_operate $1
